<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="安装日期" prop="installDate">
        <el-date-picker clearable
          v-model="queryParams.installDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择安装日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="设备位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入设备位置"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in farm_device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['device_manage:device_manage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device_manage:device_manage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device_manage:device_manage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['device_manage:device_manage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="device_manageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="equipmentId" width="50px" />
      <el-table-column label="所属风场" align="center" prop="farmName" />
      <el-table-column label="设备类型" align="center" prop="typeName" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="安装日期" align="center" prop="installDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.installDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备位置" align="center" prop="location" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="farm_device_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250px">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="getDeviceInfo(scope.row)" v-hasPermi="['device_manage:device_manage:edit']">查看详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device_manage:device_manage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device_manage:device_manage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="device_manageRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="所属风场" prop="farmId">
          <el-select v-model="form.farmId" placeholder="请选择所属风场">
            <el-option
                v-for="farm in farmList"
                :key="farm.farmId"
                :label="farm.farmName"
                :value="farm.farmId"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="设备类型" prop="equipmentType">
          <el-select v-model="form.equipmentType" placeholder="请选择设备类型">
            <el-option
                v-for="type in equipmentTypeList"
                :key="type.typeId"
                :label="type.typeName"
                :value="type.typeId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="安装日期" prop="installDate">
          <el-date-picker clearable
            v-model="form.installDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择安装日期">
          </el-date-picker>
        </el-form-item>






        <el-form-item label="设备位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入设备位置" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in farm_device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Device_manage">
import { listDevice_manage, getDevice_manage, delDevice_manage, addDevice_manage, updateDevice_manage } from "@/api/device_manage/device_manage";

import { useRoute } from 'vue-router';
import router from "@/router/index.js";
import {listFarm} from "@/api/farm_manage/farm.js";
import {listDevice_type} from "@/api/device_type/device_type.js";

const route = useRoute();

const { proxy } = getCurrentInstance();
const { farm_device_status } = proxy.useDict('farm_device_status');

const device_manageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const farmList = ref([]);
const equipmentTypeList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    farmId: null,
    equipmentType: null,
    model: null,
    installDate: null,
    location: null,
    status: null,
    deptId: null
  },
  rules: {
    farmId: [
      { required: true, message: "所属风场不能为空", trigger: "change" }
    ],
    equipmentType: [
      { required: true, message: "设备类型不能为空", trigger: "change" }
    ],
    model: [
      { required: true, message: "型号不能为空", trigger: "blur" }
    ],
    installDate: [
      { required: true, message: "安装日期不能为空", trigger: "blur" }
    ],
    location: [
      { required: true, message: "设备位置不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备管理列表 */
function getList() {
  loading.value = true;

  if(route.query.farmId !=null){
    queryParams.value.farmId = route.query.farmId;
    queryParams.value.pageNum = 1;
  }

  listDevice_manage(queryParams.value).then(response => {
    device_manageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//新增/修改查询风场
async function getEditList() {
  try {
    const [farmRes, deviceTypeRes] = await Promise.all([
      listFarm(),
      listDevice_type()
    ]);
    farmList.value = farmRes.rows;
    equipmentTypeList.value = deviceTypeRes.rows;
  } catch (error) {
    console.error('Failed to fetch farm or device type list:', error);
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    equipmentId: null,
    farmId: null,
    equipmentType: null,
    model: null,
    installDate: null,
    location: null,
    status: null,
    createTime: null,
    updateTime: null,
    updateBy: null,
    remark: null,
    createBy: null,
    deptId: null
  };
  proxy.resetForm("device_manageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  route.query.farmId = null; // 清除 farmIdA
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.equipmentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  getEditList();
  reset();
  open.value = true;
  title.value = "添加设备管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  getEditList();
  reset();
  const _equipmentId = row.equipmentId || ids.value
  getDevice_manage(_equipmentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["device_manageRef"].validate(valid => {
    if (valid) {
      const selectedFarm = farmList.value.find(farm => farm.farmId === form.value.farmId);
      form.value.deptId = selectedFarm ? selectedFarm.deptId : null;
      if (form.value.equipmentId != null) {
        updateDevice_manage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDevice_manage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _equipmentIds = row.equipmentId || ids.value;
  proxy.$modal.confirm('是否确认删除设备管理编号为"' + _equipmentIds + '"的数据项？').then(function() {
    return delDevice_manage(_equipmentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device_manage/device_manage/export', {
    ...queryParams.value
  }, `device_manage_${new Date().getTime()}.xlsx`)
}

function getDeviceInfo(row){
  router.push({
    path: 'devices/deviceFansDetail',
    query: { id: row.equipmentId ,
      farmName: row.farmName ,
      deviceType: row.typeName,
      position: row.location,
      model: row.model,
      status: row.status
    }
  });
}

getList();
</script>

<style scoped>
.el-select{
  width: 179px;
}
</style>